﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 订单商品退换货
    /// </summary>
    [Route("admin/order/refund")]
    [ApiController]
    public class OrderRefundController : ControllerBase
    {
        private readonly IOrderRefundService _orderRefundService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public OrderRefundController(IOrderRefundService orderRefundService, IUserService userService, IMapper mapper)
        {
            _orderRefundService = orderRefundService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// type：1退款2换货
        /// 示例：/admin/order/refund/1/1
        /// </summary>
        [HttpGet("{type}/{id}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.View, "type")]
        public async Task<IActionResult> GetById([FromRoute] int type, [FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _orderRefundService.QueryAsync(x => x.Type == type && x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrderRefundDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取总记录数量
        /// type：1退款2换货
        /// 示例：/admin/order/refund/view/1/count
        /// </summary>
        [HttpGet("view/{type}/count")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.View, "type")]
        public async Task<IActionResult> GetCount([FromRoute] int type, [FromQuery] RefundParameter searchParam)
        {
            var result = await _orderRefundService.QueryCountAsync(
                x => x.Type == type
                && (searchParam.Status < 0 || x.HandleStatus == searchParam.Status));
            //返回成功200
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// type：1退款2换货
        /// 示例：/admin/order/refund/view/1/10
        /// </summary>
        [HttpGet("view/{type}/{top}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.View, "type")]
        public async Task<IActionResult> GetList([FromRoute] int type, [FromRoute] int top, [FromQuery] RefundParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _orderRefundService.QueryListAsync(top,
                x => x.Type == type
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword)) || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "HandleStatus,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrderRefundDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// type：1退款2换货
        /// 示例：/admin/order/refund/1?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("{type}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.View, "type")]
        public async Task<IActionResult> GetList([FromRoute] int type, [FromQuery] RefundParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderRefundService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.Type == type
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword)) || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "HandleStatus,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrderRefundDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 申请退换货
        /// type：1退款2换货
        /// 示例：/admin/order/refund/1
        /// </summary>
        [HttpPost("{type}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Add, "type")]
        public async Task<IActionResult> Apply([FromRoute] int type, [FromBody] OrderRefundApplyDto modelDto)
        {
            //保存数据
            var result = await _orderRefundService.ApplyAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 卖家处理:同意,拒绝,退款
        /// type：1退款2换货
        /// 示例：/admin/order/refund/handle/1/1
        /// </summary>
        [HttpPut("handle/{type}/{id}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Edit, "type")]
        public async Task<IActionResult> Handle([FromRoute] int type, [FromRoute] long id, [FromBody] OrderRefundHandleDto modelDto)
        {
            //保存数据
            var result = await _orderRefundService.HandleAsync(x => x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 买家发货
        /// type：1退款2换货
        /// 示例：/admin/order/refund/return/2/1
        /// </summary>
        [HttpPut("return/{type}/{id}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Edit, "type")]
        public async Task<IActionResult> BuyDelivery([FromRoute] int type, [FromRoute] long id, [FromBody] OrderRefundBuyDto modelDto)
        {
            //保存数据
            var result = await _orderRefundService.BuyDeliveryAsync(x => x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 卖家发货
        /// type：1退款2换货
        /// 示例：/admin/order/refund/delivery/2/1
        /// </summary>
        [HttpPut("delivery/{type}/{id}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Edit, "type")]
        public async Task<IActionResult> SellerDelivery([FromRoute] int type, [FromRoute] long id, [FromBody] OrderRefundSellerDto modelDto)
        {
            //保存数据
            var result = await _orderRefundService.SellerDeliveryAsync(x => x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// type：1退款2换货
        /// 示例：/admin/order/refund/1/1
        /// </summary>
        [HttpDelete("{type}/{id}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Delete, "type")]
        public async Task<IActionResult> Delete([FromRoute] int type, [FromRoute] int id)
        {
            if (!await _orderRefundService.ExistsAsync<OrderRefund>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据不存在或已删除"));
            }
            var result = await _orderRefundService.DeleteAsync(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// type：1退款2换货
        /// 示例：/admin/order/refund/1?ids=1,2,3
        /// </summary>
        [HttpDelete("{type}")]
        [Authorize]
        [AuthorizeFilter("OrderRefund", ActionType.Delete, "type")]
        public async Task<IActionResult> DeleteByIds([FromRoute] int type, [FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _orderRefundService.DeleteAsync(x => arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 根据ID获取数据
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/1/1
        /// </summary>
        [HttpGet("/merchant/order/refund/{type}/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetById([FromRoute] int type, [FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //查询数据库获取实体
            var model = await _orderRefundService.QueryAsync(x => x.IsDelete == 0 && x.Type == type && x.MerchantId == merchantModel.Id && x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrderRefundDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/view/1/10
        /// </summary>
        [HttpGet("/merchant/order/refund/view/{type}/{top}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromRoute] int type, [FromRoute] int top, [FromQuery] RefundParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据库列表
            var resultFrom = await _orderRefundService.QueryListAsync(top,
                x => x.IsDelete == 0
                && x.Type == type
                && x.MerchantId == merchantModel.Id
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword)) || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "HandleStatus,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrderRefundDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/1?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/merchant/order/refund/{type}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromRoute] int type, [FromQuery] RefundParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderRefundService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.IsDelete == 0
                && x.Type == type
                && x.MerchantId == merchantModel.Id
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword)) || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "HandleStatus,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrderRefundDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 卖家处理:同意,拒绝,退款
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/handle/1/1
        /// </summary>
        [HttpPut("/merchant/order/refund/handle/{type}/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantHandle([FromRoute] int type, [FromRoute] long id, [FromBody] OrderRefundHandleDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //保存数据
            var result = await _orderRefundService.HandleAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 卖家发货
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/delivery/2/1
        /// </summary>
        [HttpPut("/merchant/order/refund/delivery/{type}/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantDelivery([FromRoute] int type, [FromRoute] long id, [FromBody] OrderRefundSellerDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //保存数据
            var result = await _orderRefundService.SellerDeliveryAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/1/1
        /// </summary>
        [HttpDelete("/merchant/order/refund/{type}/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantDelete([FromRoute] int type, [FromRoute] int id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            var model = await _orderRefundService.QueryAsync<OrderRefund>(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"记录[{id}]不存在或已删除"));
            }
            model.IsDelete = 1; //标记删除
            //保存到数据库
            await _orderRefundService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// type：1退款2换货
        /// 示例：/merchant/order/refund/1?ids=1,2,3
        /// </summary>
        [HttpDelete("/merchant/order/refund/{type}")]
        [Authorize]
        public async Task<IActionResult> MerchantDeleteByIds([FromRoute] int type, [FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderRefundService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //找出符合条件的记录
            var list = await _orderRefundService.QueryListAsync<OrderRefund>(1000, x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && arrIds.Contains(x.Id), WriteRoRead.Write);
            if (list.Count() == 0)
            {
                return BadRequest(ResponseMessage.Error("没有找到需要删除的记录"));
            }
            foreach (var item in list)
            {
                item.IsDelete = 1; //标记删除
            }
            //保存到数据库
            await _orderRefundService.SaveAsync();

            return NoContent();
        }
        #endregion

        #region 普通用户调用接口========================
        /// <summary>
        /// 根据ID获取数据
        /// type：1退款2换货
        /// 示例：/account/order/refund/1
        /// </summary>
        [HttpGet("/account/order/refund/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountGetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //查询数据库获取实体
            var model = await _orderRefundService.QueryAsync(x => x.IsDelete == 0 && x.UserId == userId && x.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrderRefundDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/account/order/refund?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/account/order/refund")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromQuery] RefundParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrderRefundDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderRefundService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.IsDelete == 0
                && x.UserId == userId
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword)) || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "HandleStatus,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrderRefundDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 申请退换货
        /// 示例：/account/order/refund
        /// </summary>
        [HttpPost("/account/order/refund")]
        [Authorize]
        public async Task<IActionResult> AccountApply([FromBody] OrderRefundApplyDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            modelDto.UserId = userId;
            //保存数据
            var result = await _orderRefundService.ApplyAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 买家发货
        /// 示例：/account/order/refund/return/1
        /// </summary>
        [HttpPut("/account/order/refund/return/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountDelivery([FromRoute] long id, [FromBody] OrderRefundBuyDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            //保存数据
            var result = await _orderRefundService.BuyDeliveryAsync(x => x.Id == id, modelDto);
            return NoContent();
        }
        #endregion
    }
}
